package br.com.velp.vskygeo.generic;

import br.com.velp.vskygeo.comum.SpringConstants;
import java.io.Serializable;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * <sumario>
 * <objetivo>"Rastreabilidade"</objetivo>
 * <autor>EDUARDO SANTOS DE OLIVEIRA</autor>
 * <versao>1.0.0.0</versao>
 * <data_criacao> 06.08.2013 </data_criacao>
 * <data_ultima_alteracao> N/A </data_ultima_alteracao>
 * <descricao> Template Utilizado Para a Realização das Operações 
 *             Comuns Entre os DAO's            
 * </descricao>
 * </sumario>
 */
@Repository("hibernateTemplatePostgreDAO")
@Lazy(SpringConstants.LAZY_BEANS)
@Transactional(value = "txManagerPostgres", readOnly = true)
public abstract class HibernateTemplatePostgreDAO<T> implements Serializable {
    
    @Autowired
    @Qualifier("sessionFactoryPostgres")
    private SessionFactory sessionFactory;
    
    public T obterPorId(Class clazz, Serializable id) {
        return (T) getSession().get(clazz, id);
    }
    
    @Transactional(readOnly = false)
    public T salvar(T value) throws Exception {
        T object = (T) getSession().save(value);
        getSession().flush();
        return object;
    }
    
    @Transactional(readOnly = false)
    public void atualizar(T value) throws Exception {
        getSession().update(value);
        getSession().flush();
    }
    
    @Transactional(readOnly = false)
    public void salvarOuAtualizar(T value) throws Exception {
        getSession().saveOrUpdate(value);
        getSession().flush();
    }
    
    @Transactional(readOnly = false)
    public void excluir(T value) throws Exception {
        getSession().delete(value);
        getSession().flush();
    }
    
    public Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }
    
}
